import 'package:bloc/bloc.dart';
import 'package:hive/hive.dart';
import 'package:meta/meta.dart';

import '../../../api/api_client.dart';
import '../../../models/user.dart';

part 'home_btm_more_event.dart';
part 'home_btm_more_state.dart';

class HomeBtmMoreBloc extends Bloc<HomeBtmMoreEvent, HomeBtmMoreState> {
  final ApiClient apiClient;
  HomeBtmMoreBloc({required this.apiClient}) : super(HomeBtmMoreState()) {
    on<HomeBtmMoreEvent>(_onHomeBtmMoreEvent);
    on<HomeBtmYearEvent>(_onLoadHomeData);
    on<HomeBtmYearJiDuEvent>(_onLoadHomeJiDuData);
  }


  void _onHomeBtmMoreEvent(HomeBtmMoreEvent event, Emitter<HomeBtmMoreState> emit) {

    // emit(HomeBtmMoreState());
  }

  int year = DateTime.now().year;
  int jidu = 0;

  final List<String> jiduStart = ['01', '03', '06', '09'];
  final List<String> jiduEnd = ['03', '06', '09', '12'];


  Future<void> _onLoadHomeData( HomeBtmYearEvent event, Emitter<HomeBtmMoreState> emit) async {
    try {
      final user = Hive.box<User>('user_box').get('currentUser');
      year = event.year;
      final summary = await apiClient.getFinancialSummary(user?.appCompanyDto?.taxCode?? '', '${event.year}');
      print(' ---- HomeBtmMoreBloc------->: ${summary.data}');
      emit(state.copyWith(data: summary.data));
    } catch (e) {
    }
  }

  Future<void> _onLoadHomeJiDuData( HomeBtmYearJiDuEvent event, Emitter<HomeBtmMoreState> emit) async {
    try {
      final user = Hive.box<User>('user_box').get('currentUser');
      var index = event.jidu;
      final summary = await apiClient.homeDateQuarter(user?.appCompanyDto?.taxCode?? '',  '${year}${jiduStart[index]}',  '${year}${jiduEnd[index]}');
      print(' ---- _onLoadHomeJiDuData------->: ${summary.data}');
      emit(state.copyWithBtn(btmData: summary.data));
    } catch (e) {
    }
  }


}
